package com.zhijian.medical.job;

import com.zhijian.medical.entity.po.Assessment;
import com.zhijian.medical.entity.vo.response.RoutinePathologyTsVo;
import com.zhijian.medical.enums.AssessmentStatusEnum;
import com.zhijian.medical.service.AssessmentService;
import com.zhijian.medical.service.CacheService;
import com.zhijian.medical.service.RoutinePathologyTsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author HCG
 * @version 1.0
 * @date 2022/3/20
 */
@Service
@Slf4j
public class AssessmentTurnStatusJob {

    @Autowired
    private AssessmentService assessmentService;

    @Autowired
    private CacheService cacheService;
    @Autowired
    private RoutinePathologyTsService tsService;

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Scheduled(cron = "${job.point.cron:0 0 1 * * * }")
//    @Scheduled(cron = "${job.point.cron:0 * * * * * }")
    public void handle() {
        Date now = new Date();
        //未开始
        List<Assessment> unStartAssessmentList = assessmentService.selectByStatus(AssessmentStatusEnum.UN_START.getCode().byteValue());

        unStartAssessmentList.forEach(assessment -> {
            if (assessment.getStartTime().before(now)) {
                //如果开始时间已经在当前时间前面，就改成进行中
                assessmentService.updateByPrimaryKeySelective(Assessment.builder()
                        .id(assessment.getId())
                        .status(AssessmentStatusEnum.RUNNING.getCode().byteValue())
                        .updateTime(now)
                        .build());
            }
        });

        //进行中
        List<Assessment> runningAssessmentList = assessmentService.selectByStatus(AssessmentStatusEnum.RUNNING.getCode().byteValue());

        runningAssessmentList.forEach(assessment -> {
            if (assessment.getEndTime().before(now)) {
                //如果结束时间已经在当前时间前面，就改成已结束
                assessmentService.updateByPrimaryKeySelective(Assessment.builder()
                        .id(assessment.getId())
                        .status(AssessmentStatusEnum.END.getCode().byteValue())
                        .updateTime(now)
                        .build());
            }
        });

    }


    @Scheduled(cron = "${job.point.cron:0/1 * * * * ? }")
    public void cache() {
        RoutinePathologyTsVo tsVo = tsService.selectVoById(1L);
        // 结算剩余时间
        Long ttl = cacheService.ttl("gl_step_ts_time/" + tsVo.getSample());
//        System.out.println(ttl);
    }
}
